<template>
  <a-modal
    :open="open"
    :title="title"
    :width="width"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      layout="horizontal"
      @submit.prevent
      :validate-trigger="['blur', 'change']"
    >
      <slot :form-data="formData" />
    </a-form>
  </a-modal>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const props = defineProps({
  open: {
    type: Boolean,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  width: {
    type: [String, Number],
    default: 600
  },
  loading: {
    type: Boolean,
    default: false
  },
  initialValues: {
    type: Object,
    default: () => ({})
  },
  rules: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:open', 'submit', 'cancel'])

const formRef = ref(null)
const formData = ref({ ...props.initialValues })

// 监听 initialValues 变化
watch(
  () => props.initialValues,
  (newValues) => {
    formData.value = { ...newValues }
  },
  { deep: true, immediate: true }
)

// 监听 open 状态变化
watch(
  () => props.open,
  (newValue) => {
    if (newValue) {
      formData.value = { ...props.initialValues }
      // 重置表单验证状态
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
  }
)

const handleSubmit = async () => {
  try {
    // 触发表单验证
    const values = await formRef.value.validateFields()
    // 提交表单数据
    emit('submit', values)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields()
  }
  emit('update:open', false)
  emit('cancel')
}

// 组件挂载时初始化表单数据
onMounted(() => {
  formData.value = { ...props.initialValues }
})
</script>

<style scoped>
:deep(.ant-modal-content) {
  border-radius: var(--border-radius-lg);
  overflow: hidden;
}

:deep(.ant-modal-header) {
  border-bottom: 1px solid var(--border-color);
  padding: var(--spacing-lg);
}

:deep(.ant-modal-body) {
  padding: var(--spacing-lg);
}

:deep(.ant-modal-footer) {
  border-top: 1px solid var(--border-color);
  padding: var(--spacing-lg);
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-input),
:deep(.ant-input-number),
:deep(.ant-select-selector) {
  border-radius: var(--border-radius-base);
}

/* 暗色主题适配 */
[data-theme='dark'] :deep(.ant-modal-content) {
  background: var(--background-color-dark);
}

[data-theme='dark'] :deep(.ant-modal-header),
[data-theme='dark'] :deep(.ant-modal-footer) {
  border-color: var(--border-color);
}

/* 响应式布局 */
@media (max-width: 768px) {
  :deep(.ant-modal-content) {
    margin: var(--spacing-md);
  }

  :deep(.ant-form-item-label),
  :deep(.ant-form-item-control) {
    flex: 0 0 100%;
    max-width: 100%;
  }
}
</style> 